<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" border stripe>
        <el-table-column lable="文章标题" prop="title"></el-table-column>
        <el-table-column lable="分类" prop="cate_name"></el-table-column>
        <el-table-column lable="发表时间">
          <template v-slot:default="obj">
            <span>{{ obj.row.pub_date | dtformat }}</span>
          </template>
        </el-table-column>
        <el-table-column lable="状态" prop="state"></el-table-column>
        <el-table-column lable="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 对话框区域 -->
    <el-dialog title="发表文章" :visible.sync="pubVisible" fullscreen :before-close="handleClose" @closed="onDialog">
      <el-form :model="pubForm" :rules="pubFormRules" label-width="80px" ref="pubFormRef">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择文章分类" style="width: 100%">
            <el-option label="请选择分类" value=""></el-option>
            <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img :src="url" alt="" class="cover-img" ref="imgRef" v-if="url" />
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" v-else />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none" ref="iptFileRef" accept="image/*" @change="onCoverChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pub('已发布')">发布</el-button>
          <el-button type="info" @click="pub('草稿')">存为草稿</el-button></el-form-item
        >
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCateListAPI } from '@/api/artCate.js'
import { bookCateAPI, getArtListAPI, deleteListAPI } from '@/api/article.js'
export default {
  name: 'CrtList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1, // 页码值
        pagesize: 2, // 每页显示多少数据
        cate_id: '', // 筛选的条件 分类的id
        state: '' // 筛选的条件 文章选中的状态
      },
      // 控制发表对话框的显示与隐藏
      pubVisible: false,
      // 发表文章表单的基础数据
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      url: '',
      // 文章分类
      cateList: [],
      pubFormRules: {
        title: [{ required: true, message: '必填项', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }]
      },
      // 文章的列表数据
      artList: [],
      total: 0
    }
  },
  created() {
    this.initCateList()
    this.initArtList()
  },
  methods: {
    // 对话框关闭之前会触发这个函数
    // 形参中的done决定了是否关闭对话框
    // done是一个函数
    async handleClose(done) {
      const result = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return done(false)
      done()
    },
    // 初始化文章分类的列表数据
    async initCateList() {
      const { data: res } = await getCateListAPI()
      if (res.code !== 0) return this.$message.error(res.message)
      this.cateList = res.data
    },
    chooseImg() {
      this.$refs.iptFileRef.click()
    },
    // 监听文件选择框的 change 事件
    onCoverChange(e) {
      // 获取到用户选择的封面
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
      } else {
        // 用户选择了封面
        this.pubForm.cover_img = files[0]

        this.url = URL.createObjectURL(files[0])
      }
    },
    // 点击发表状态并检验值是否合规
    pub(state) {
      // 设置文章的发表状态
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(valid => {
        if (!valid) return this.$message.error('请完善文章信息！')
      })
      if (this.pubForm.cover_img === null) return this.$message.error('请添加封面！')
      this.addbookCate()
    },
    onDialog() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.url = ''
    },
    async addbookCate() {
      const fd = new FormData()
      for (const k in this.pubForm) {
        fd.append(k, this.pubForm[k])
      }
      const { data: res } = await bookCateAPI(fd)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.pubVisible = false
      this.initArtList()
    },
    // 获取文章列表数据
    async initArtList() {
      const { data: res } = await getArtListAPI(this.q)
      if (res.code !== 0) return this.$message.error(res.message)
      this.artList = res.data
      this.total = res.total
    },
    // 页面展示的数据条数,发生了变化
    handleSizeChange(newSize) {
      this.q.pagesize = newSize
      this.initArtList()
    },
    // 页码值发生变化时会触发这个函数
    handleCurrentChange(newPage) {
      this.q.pagenum = newPage
      this.initArtList()
    },
    search() {
      this.q.pagenum = 1
      this.initArtList()
    },
    reset() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    // 删除文章
    async remove(id) {
      const result = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return
      const { data: res } = await deleteListAPI(id)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 每当删除成功的时候, 判断artList数组的length是否为1
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.initArtList()
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}

// 解决元素对齐问题
/deep/ .ql-snow .ql-picker-label::before {
  position: relative;
  top: -8px;
}

// 解决元素对齐问题
/deep/ .ql-picker-label > svg {
  position: relative;
  top: -6px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
